<template>
  <div class="layout-padding">
    <div class="layout-padding-auto layout-padding-view">
      <!--  标题行    -->
      <el-row :gutter="20" style="margin: 0px -60px 20px 5px;">
        <el-col :span="18"><h1 class="my-heading">资料列表</h1></el-col>
<!--        <el-col :span="2">-->
<!--          <el-button icon="folder-add" type="primary" class="ml10" @click="goKszlFile(0)" v-auth="'train_kszlData_add'">新 增</el-button>-->
<!--        </el-col>-->
<!--        <el-col :span="3">-->
<!--          <el-button plain :disabled="multiple" icon="Delete" type="primary" v-auth="'train_kszlData_del'" @click="handleDelete(selectObjs)">批量删除</el-button>-->
<!--        </el-col>-->
      </el-row>

      <el-row v-show="showSearch">
        <el-form :model="state.queryForm" ref="queryRef" :inline="true" @keyup.enter="getDataList" style="width: 100%">
          <el-form-item label="资料名称" prop="dataName" >
            <el-input v-model="state.queryForm.dataName" clearable placeholder="请输入资料名称"/>
          </el-form-item>
          <el-form-item  label="学习组织" prop="studyGroupIds" style="width: 260px">
            <el-cascader v-model="state.queryForm.studyGroupIds" ref="cascaderAddr" style="width: 500px" @visible-change="handleVisibleChange" filterable
                         placeholder="请选择标签" @change="handleCascaderChange" :props="{ value: 'id', label: 'name', children: 'children',checkStrictly: true }"
                         :options="options1" clearable>
            </el-cascader>
          </el-form-item>
          <el-form-item label="学习岗位" prop="studyPost" style="width: 260px">
            <el-select @change="getItem1" v-model="state.queryForm.studyPost" filterable multiple clearable collapse-tags collapse-tags-tooltip  placeholder="请选择" >
              <el-option v-for="item in postList" :key="item.postsString" :label="item.postName" :value="item.postName"/>
            </el-select>
          </el-form-item>
          <el-form-item label="专业名称" prop="majorNameIds" style="width: 260px">
            <el-select @change="getItem3" v-model="state.queryForm.majorNameIds" filterable clearable multiple collapse-tags collapse-tags-tooltip  placeholder="请选择" >
              <el-option v-for="item in options2"   :key="item.zymcId" :label="item.zymcName" :value="item.zymcId"/>
            </el-select>
          </el-form-item>
          <el-form-item label="关键点" prop="keyPoints" >
            <el-select @change="getItem2" v-model="state.queryForm.keyPointIds" filterable multiple clearable collapse-tags collapse-tags-tooltip  placeholder="请选择" >
              <el-option v-for="item in keypointsListData"  :key="item.keyId" :label="item.zymcName+'-'+item.keyPoint" :value="item.keyId"/>
            </el-select>
          </el-form-item>
          <el-form-item style="width: 15%;">
            <el-button icon="search" type="primary" @click="getDataList">查询</el-button>
            <el-button icon="Refresh" @click="resetQuery" >重置</el-button>
          </el-form-item>
          <el-form-item>
            <el-button icon="folder-add" type="primary"  @click="goKszlFile(0)">新 增</el-button>
            <el-button plain :disabled="multiple" icon="Delete" type="primary"  @click="handleDelete(selectObjs)">批量删除</el-button>
          </el-form-item>
        </el-form>
      </el-row>
      <el-row>
<!--        <div class="mb8" style="width: 100%">-->
<!--          <right-toolbar v-model:showSearch="showSearch" :export="'train_kszlData_export'" @exportExcel="exportExcel" class="ml10 mr20" style="float: right;" @queryTable="getDataList"></right-toolbar>-->
<!--        </div>-->
      </el-row>
      <el-table :data="state.dataList" v-loading="state.loading" border
                :cell-style="tableStyle.cellStyle" :header-cell-style="tableStyle.headerCellStyle"
                @selection-change="selectionChangHandle"
                @sort-change="sortChangeHandle">
        <el-table-column type="selection" width="40" align="center" />
        <el-table-column type="index" label="#" width="50" />
        <el-table-column prop="dataName" label="资料名称"  show-overflow-tooltip min-width="150"/>
        <!--          <el-table-column prop="dataFileId" label="资料文件主键id" width="100"  show-overflow-tooltip/>-->
        <el-table-column prop="studyGroupId" label="学习组织"  :formatter="formatter" show-overflow-tooltip/>
        <el-table-column prop="studyPost" label="学习岗位"  show-overflow-tooltip/>
        <el-table-column prop="majorNameId" label="专业名称"  :formatter="formatter1" show-overflow-tooltip/>
        <el-table-column prop="keyPoint" label="关键点"  show-overflow-tooltip/>
        <el-table-column prop="dataType" label="资料类型"  show-overflow-tooltip width="100"/>
        <el-table-column prop="createTime" label="创建时间"  show-overflow-tooltip/>
        <el-table-column prop="createBy" label="创建人员"  show-overflow-tooltip width="100"/>
        <el-table-column label="操作" width="300">
          <template #default="scope">
            <el-button icon="edit-pen" text type="primary" v-auth="'train_kszlData_edit'" @click="goKszlFile(1,scope.row.dataFileId,scope.row.dataId)">编辑</el-button>
            <el-button icon="delete" text type="primary" v-auth="'train_kszlData_del'" @click="handleDelete([scope.row.dataFileId],scope.row)">删除</el-button>
            <el-button icon="Star" text type="primary" v-if="scope.row.queryFlag==1" @click="handleQuestion(scope.row)">疑问点</el-button>
            <el-button icon="folder-add" text type="primary" @click="handleTest(scope.row)">试题数量</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" v-bind="state.pagination" />
    </div>

    <!-- 编辑、新增  -->
    <form-dialog ref="formDialogRef" @refresh="getDataList(false)" />
    <!-- 疑问点  -->
    <el-dialog v-model="dialogVisible" :title="fileName+'--'+'疑问点'" width="30%">
      <el-table :data="questionList" style="width: 100%" border>
        <el-table-column prop="personName" label="姓名" width="120" />
        <el-table-column prop="reason" label="提出异议原因"  />
        <el-table-column prop="createTime" label="时间"  />
      </el-table>
    </el-dialog>
    <!-- 试题数量  -->
    <el-dialog v-model="dialogVisible1" :title="fileName+'--'+'试题数量'" width="20%">
      <el-table :data="testList" style="width: 72%;margin-left: 40px;font-size: 18px" border>
        <el-table-column prop="questionType" label="题型" show-overflow-tooltip>
          <template #default="scope">
            <dict-tag :options="tkgl_topic_type" :value="scope.row.questionType"></dict-tag>
          </template>
        </el-table-column>
        <el-table-column prop="count" label="题数(道)" width="120" align="center"/>
      </el-table>
    </el-dialog>

  </div>
</template>

<script setup lang="ts" name="systemKszlData">
  //导入
  import mittBus from '/@/utils/mitt';
  import { BasicTableProps, useTable } from "/@/hooks/table";
  import { useMessage, useMessageBox } from "/@/hooks/message";
  import { useDict } from '/@/hooks/dict';
  import { useRouter } from 'vue-router';
  import {professionalnameList} from "/@/api/train/jnglProfessionLevel";
  import {fetchList, delObjs, deptTree, syspost, getQueryList, getTestList} from "/@/api/train/kszlData";
  import {keypointsList, office} from "/@/api/train/kszlFile";
  import {ref} from "vue";
  import {getKeyPointListByZymcIds} from "/@/api/train/ksglExamList";
  // 定义查询字典
  const cascaderAddr = ref<InstanceType<typeof import('element-plus/es/components/cascader')>>(null);
  const { tkgl_topic_type } = useDict('tkgl_topic_type')
  const router = useRouter();
  // 引入组件
  const FormDialog = defineAsyncComponent(() => import('./form.vue'));
  // 定义变量内容
  const formDialogRef = ref()
  // 搜索变量
  const queryRef = ref()
  const treeDataValue = ref()
  //学习组织数据
  const options1 = ref<any[]>([]);
  //关键点
  const keypointsListData = reactive([])
  //疑问点
  const questionList = reactive([{}])
  const fileName = ref()
  const groupId = ref()
  //专业名称数据
  const options2 =reactive([])
  const sendData =reactive([{}])
  //学习岗位
  const postList =reactive([])
  //相关试题
  const testList =reactive([{}])
  const queryForm =reactive({})
  const showSearch = ref(true)
  // 多选变量
  const selectObjs = ref([]) as any
  const selectObjsOffice = ref([]) as any
  const multiple = ref(true)
  //部门主键
  const pkDept = ref()
  const questionTypeResult = ref()
  const studyGroup = ref()
  const zymcArr = ref([])
  //弹框显示
  const dialogVisible = ref(false)
  const dialogVisible1 = ref(false)
  const state: BasicTableProps = reactive<BasicTableProps>({
    queryForm: {},
    pageList: fetchList
  })
  const officeUrl = ref()
  //  table hook
  const {
    getDataList,
    currentChangeHandle,
    sizeChangeHandle,
    sortChangeHandle,
    downBlobFile,
    tableStyle
  } = useTable(state)
  //挂载完毕
  onMounted(()=>{
    deptTreeList()
    getProfessionalName()
    getKeypointsList()
    office().then((res)=>{
      officeUrl.value = res.data
    })
  })
  // 清空搜索条件
  const resetQuery = () => {
    state.queryForm.majorNameId = ''
    state.queryForm.keyPointIds = []
    state.queryForm.keyPointIds = ''
    state.queryForm.keyPointId = ''
    state.queryForm.studyPostIds = ''
    state.queryForm.studyGroupId = ''
    // 清空搜索条件
    queryRef.value?.resetFields()
    // 清空多选
    selectObjs.value = []
    getDataList()
  }
  //跳转页面
  const goKszlFile =(state:number,id:string,dataId:string) =>{
    // console.log('id---------',id)
    const path = '/train/kszlFile/index';
    const sendId1 = { state,id,dataId }
    // console.log('send1-----',sendId1)
    router.push({path, query: sendId1 })
  }
  const handleCascaderChange = (item: any) => {
   if(item!==null){
     state.queryForm.studyGroupId = item.join('/')
     groupId.value = item[item.length-1]
   }
    state.queryForm.studyPosts = []
    state.queryForm.studyPost = []
    // console.log('handleCascaderChange',item,groupId.value)
  };
  //参考组织下拉框关闭事件
  const handleVisibleChange = (isVisible:any) => {
    if (!isVisible) {
      if (cascaderAddr.value) {
        const checkedNodes = cascaderAddr.value.getCheckedNodes(); // 输出选中的节点信息
        groupId.value = checkedNodes[0].value
      }
      getPostList()
    }
  };
  const getItem1=(val:any) =>{
    let arr = []
    postList.forEach(item => {
      for (let i = 0; i < val.length; i++) {
        if (item.postName == val[i]) {
          arr.push(item.postsString)
          // console.log('arr',arr)
        }
      }
    })
    state.queryForm.studyPostIds = arr.join(',')
  }
  const getItem2=(val:any) =>{
    state.queryForm.keyPointId = val.join(',')
  }
  const getItem3=(val:any) =>{
    zymcArr.value = val
    state.queryForm.majorNameId = val.join(',')
    state.queryForm.keyPointIds = []
    getKeypointsList()
  }
  //关键点
  const  getKeypointsList = () =>{
    keypointsListData.length = 0
    const ids = {
      zymcIds:  zymcArr.value
    }
    // console.log(' queryForm----', ids,queryForm)
    getKeyPointListByZymcIds(ids).then((res: any) => {
      Object.assign(keypointsListData, res.data)
    });
  }
  // 导出excel
  const exportExcel = () => {
    downBlobFile('/train/kszlData/export', Object.assign(state.queryForm, { ids: selectObjs }), 'kszlData.xlsx')
  }
  // 多选事件
  const selectionChangHandle = (objs: { id: string }[]) => {
    // console.log('objs',objs)
    selectObjs.value = objs.map(({ dataFileId }) => dataFileId);
    selectObjsOffice.value = objs.map(({ onlyOfficeId }) => onlyOfficeId);
    // console.log('selectObjsOffice.value',selectObjsOffice.value)
    multiple.value = !objs.length;
  };
  //专业名称
  const  getProfessionalName = () => {
    professionalnameList().then((res) => {
      Object.assign(options2, res.data)
    });
  };
  //疑问点
  const handleQuestion = (row:any) =>{
    questionList.length = 0
    fileName.value = row.dataName
    dialogVisible.value = true
    const id1 = {
      dataId:row.dataId
    }
    // console.log('id1',row,id1)
    getQueryList(id1).then((res)=>{
      Object.assign(questionList, res.data.records)
    })
  }
  //相关试题
  const handleTest = (row:any) =>{
    fileName.value = row.dataName
    const id = row.dataId
    dialogVisible1.value = true
    testList.length = 0
    getTestList(id).then((res)=>{
      Object.assign(testList, res.data.data)
    })
  }
  // 参与组织
  const deptTreeList = async () => {
    deptTree().then((res) => {
      options1.value = res.data;
    });
  };
  const formatter = (row:any) =>{
    return  row.studyGroup
  }
  const formatter1 = (row:any) =>{
    return  row.majorName
  }
  //学习岗位
  const getPostList =  () =>{
    // console.log('groupId.value',groupId.value )
    postList.length = 0
    const num = groupId.value
    syspost(num).then((res: any) => {
      Object.assign(postList, res.data)
    });
  }
  // 删除操作
  const handleDelete = async (ids: string[],row:any) => {
    for(let i = 0; i<selectObjsOffice.value.length;i++){
      // console.log('selectObjsOffice.value.length',selectObjsOffice.value.length)
      // const url = `${officeUrl.value}/delete/${row.onlyOfficeId}`;
      const url = `${officeUrl.value}/delete?id=${selectObjsOffice.value[i]}`;
      fetch(url, {
        method: 'GET', // 指定请求方法
        headers: {
          'Content-Type': 'application/json', // 根据需要设置请求头
          // 如果有认证token，也可以在这里添加
          // 'Authorization': 'Bearer YOUR_TOKEN'
        },
      })
              .then(response => {
                // console.log('111111-111111111111')
                if (!response.ok) {
                  throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
              })
              .then(data => {
                console.log('Delete successful:', data);
                // 处理删除成功后的逻辑
              })
              .catch(error => {
                console.error('There has been a problem with your fetch operation:', error);
                // 处理错误
              });
    }

    try {
      await useMessageBox().confirm('此操作将永久删除');
    } catch {
      return;
    }
    try {
      await delObjs(ids);
      getDataList();
      useMessage().success('删除成功');
    } catch (err: any) {
      useMessage().error(err.msg);
    }
  };
</script>
<style lang="scss" scoped>
  .my-heading {
    color: black;
    font-weight: bold;
    font-size: 26px;
    margin-bottom: 10px;
  }
  .el-form-item{
    width: 220px;
  }
  .el-cascader-panel .el-radio{
    width: 100%;
    height: 100%;
    z-index: 10;
    position: absolute;
    top: 10px;
    right: 10px;
  }
  .el-cascader-panel .el-radio__input{
    visibility: hidden;
  }
  .el-cascader-panel .el-cascader-node__postfix {
    top: 10px;
  }
  .el-form-item__content{
    margin-right: -5px !important;
  }
</style>